#include "sharedSemaphore.h"


//============================================================================

// Define a class based on POSIX semaphore functions.


sharedSemaphore::sharedSemaphore( )
{
	_sem_key = (key_t)KEY;
	_sem_id = -1;
	_sem_id = semget(_sem_key, 0, 0);
	mode_t sem_mode = IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
	union semun      arg;

	if( _sem_id == -1 ) {
		_sem_id = (int) semget(_sem_key, 1, sem_mode);
		if(_sem_id == -1) {
			if (errno == EEXIST) {
				perror("IPC error 1: semget");
			}
			else {
				perror("IPC error 2: semget");
			}
			exit(1);
		}
		arg.val = 1;

		if(semctl(_sem_id, 0, SETVAL, arg) == -1)
			exit(1);
	}

}

sharedSemaphore::~sharedSemaphore( void )
{

}

void sharedSemaphore::wait( void )
{
	struct sembuf sops;
	sops.sem_num = 0;
	sops.sem_op = -1;
	sops.sem_flg = SEM_UNDO;
	semop(_sem_id, &sops, 1);
}

void sharedSemaphore::signal( void )
{
	struct sembuf sops;
	sops.sem_num = 0;
	sops.sem_op = 1;
	sops.sem_flg = SEM_UNDO;
	semop(_sem_id, &sops, 1);
}
